using UnityEngine;

public class ZooPlatformGenerator : MonoBehaviour
{
    public static ZooPlatformGenerator instance;

    [Header("Platform Setup")]
    [SerializeField] private ZooPiece[] zooPieces;
    [SerializeField] private int platformCount = 8;
    [SerializeField] private Transform platformContainer;

    [Header("End Piece")]
    [SerializeField] private GameObject endPrefab;  // final prefab with trigger
    [SerializeField] private Vector2 endOffset = new Vector2(12f, 0f);
    [SerializeField] private Vector2 startPos = new Vector2(12f, 0f);

    private Vector2 nextPiecePos;

    private void Awake()
    {
        if (ZooPlatformGenerator.instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(gameObject);
        }
    }

    // Generates a new random level
    public void GenerateLevel()
    {
        ClearLevel(); // ensure clean state
        nextPiecePos = startPos;

        // --- Spawn random zoo pieces ---
        for (int i = 0; i < platformCount; i++)
        {
            ZooPiece nextPiece = zooPieces[Random.Range(0, zooPieces.Length)];

            Instantiate(
                nextPiece.prefab,
                new Vector3(nextPiecePos.x + nextPiece.offset.x, nextPiecePos.y + nextPiece.offset.y, 0),
                Quaternion.identity,
                platformContainer
            );

            nextPiecePos += nextPiece.newPos;
        }

        // --- Spawn the END piece ---
        if (endPrefab != null)
        {
            Vector3 endPos = new Vector3(
                nextPiecePos.x + endOffset.x,
                nextPiecePos.y + endOffset.y,
                0
            );

            Instantiate(endPrefab, endPos, Quaternion.identity, platformContainer);
        }
        else
        {
            Debug.LogWarning("[ZooPlatformGenerator] End Prefab is not assigned!");
        }
    }

    // Removes all existing platform pieces
    public void ClearLevel()
    {
        if (platformContainer == null)
        {
            Debug.LogWarning("[ZooPlatformGenerator] Platform container is missing.");
            return;
        }

        // Destroy all child objects inside the container
        for (int i = platformContainer.childCount - 1; i >= 0; i--)
        {
            Destroy(platformContainer.GetChild(i).gameObject);
        }
    }
}
